//
//  WBMainViewController.swift
//  传智微博
//
//  Created by zhoujiming on 2016/12/15.
//  Copyright © 2016年 gmcc. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    fileprivate var timer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        
        setComposeButton()
        
        setupTimer()
        
        // 设置新特性视图
        setupNewFeatureViews()
        
        delegate = self
        // Do any additional setup after loading the view.
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogon), name: NSNotification.Name(rawValue: WBUserShouldLogonNotification), object: nil)
        
    }
    deinit {
        
        //  销毁时钟
        timer?.invalidate()
        
        NotificationCenter.default.removeObserver(self)
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // MARK: - 监听方法
    @objc private func userLogon(n : Notification){
        print("用户登录通知\(n)")
        var deadline = DispatchTime.now()
        // 判断n。object是否有值，如果有，则弹出提示框
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            
            deadline = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: deadline){
            SVProgressHUD.setDefaultMaskType(.clear)
            // 展现登录控制器 - 通常会和UINavigationController联用，以便返回
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    // 撰写微博 FIXME: 没有实现
    @objc fileprivate func compseStatus() -> (){
        print("撰写微博")
        
        // 测试方向
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController : vc)
        
        present(nav, animated: true, completion: nil)
        
    }
    // MARK: - 定义私有控件
    lazy  var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

}

extension WBMainViewController : UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        
        let index = (childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex == 0 && index == selectedIndex {
            print("点击首页")
            let nav = childViewControllers[0] as! UINavigationController
            
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            
            // 清除tabbaritem的badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK:时钟相关方法
extension WBMainViewController{
    fileprivate func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 150.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc fileprivate func updateTimer(){
        if !WBNetworkManager.shared().userLogon {
            return
        }
        WBNetworkManager.shared().unreadCount { (count) in
            print("检测到\(count)条新微博")
            
            // 设置首页的badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            UIApplication.shared.applicationIconBadgeNumber = count
        }

    }
}

// MARK: 新特性视图处理
extension WBMainViewController{
    // 设置新特性视图
    fileprivate func setupNewFeatureViews(){
        // 0.如果没有登录，啥都不做
        if !WBNetworkManager.shared().userLogon {
            return
        }
        
        // 1.如果更新，显示新特性
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomView.welcomeView()
        
        // 2.添加视图
        //v.frame = view.bounds
        view.addSubview(v)
        
    }
    
    fileprivate var isNewVersion: Bool{
        // 取当前的版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        // 取之前的版本号
        let path = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = try? String(contentsOfFile: path!) ?? ""
        
        // 将当前版本号保存在沙盒
        try? currentVersion.write(toFile: path!, atomically: true, encoding: .utf8)
        // 返回版本号是否一致
        
        return currentVersion != sandboxVersion
        //return currentVersion == sandboxVersion
    }
}
extension WBMainViewController{
    // 设置撰写按钮
     fileprivate func setComposeButton()
     {
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        composeButton.frame = tabBar.bounds.insetBy(dx : 2 * w, dy : 0)
        
        composeButton.addTarget(self, action: #selector(compseStatus), for: .touchUpInside)
    }
    fileprivate func setupChildControllers()
    {
        // 获取沙盒json路径
        let doc = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonpath = (doc as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonpath)
        
        // 判断data是否有内容
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : AnyObject]] else{
            return
        }
        
        
//        let array = [
//            ["clsName" : "WBHomeViewController", "title": "首页", "imageName": "home",
//             "visitorInfo":["imageName":"", "message":"关注一些人"]
//            ],
//            ["clsName" : "WBMessageViewController", "title": "消息", "imageName": "message_center",
//             "visitorInfo":["imageName":"visitordiscover_image_message", "message":"别人评论你的微博"]
//            ],
//            ["clsName" : "UIViewController"],
//            ["clsName" : "WBDiscoverViewController", "title": "发现", "imageName": "discover",
//             "visitorInfo":["imageName":"visitordiscover_image_message", "message":"尽在掌握"]
//            ],
//            ["clsName" : "WBProfileViewController", "title": "我", "imageName": "profile",
//             "visitorInfo":["imageName":"visitordiscover_image_profile", "message":"展示给别人"]
//            ]
//        ]
//        
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/zhoujm/Desktop/demo.json", atomically: true)
        
        //(array as NSArray).write(toFile: "/Users/mac/Desktop/demo.plist", atomically: true)
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        
        viewControllers = arrayM
    }
    
    private func controller(dict : [String : AnyObject]) -> UIViewController
    {
        // 取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls  = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String]
            else
        {
            return UIViewController()
        }
        
        // 创建视图控制器
        let vc = cls.init()
        
        vc.visitorInfoDictionary = visitorDict
        
        vc.title = title
        
        // 设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        
        //vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 24)], for: UIControlState(rawValue: 0))
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    
    }
}
